package com.thyme.web.controller;


import com.thyme.dto.FileInfo;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;

/**
 * @author ah.caixiaodong@aisino.com
 * @ClassName FileController
 * @Description TODO
 * @Date 2019/6/6 14:38
 */
@RestController
@RequestMapping("/file")
public class FileController {

    private static final Logger logger = LoggerFactory.getLogger(FileController.class);

    private String folder = "E:/BaiduNetdiskDownload";

    @PostMapping
    public FileInfo upload(MultipartFile file) throws Exception {
        logger.info(file.getName());
        logger.info(file.getOriginalFilename());
        System.out.println(file.getSize());
        File localFile = new File(folder,System.currentTimeMillis()+".txt");
        file.transferTo(localFile);
        return new FileInfo(localFile.getAbsolutePath());
    }

    @GetMapping("/{id}")
    public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws Exception{
        try (InputStream inputStream = new FileInputStream(new File(folder,id + ".txt"));
             OutputStream outputStream = response.getOutputStream();){
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition","attachment;filename=test.txt");
            IOUtils.copy(inputStream,outputStream);
            outputStream.flush();
        }
    }
}
